package com.tczs.client;

import com.alibaba.fastjson.JSONObject;
import com.tczs.client.service.ClientService;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.util.CharsetUtil;
import org.apache.log4j.Logger;

@ChannelHandler.Sharable
public class ClientHandler  extends SimpleChannelInboundHandler<ByteBuf>{

    private static Logger logger = Logger.getLogger(ClientHandler.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("客户端:"+ctx.channel().id()+" 连接成功");
//        System.out.println("激活了");
//        ChannelFuture future = ctx.channel().writeAndFlush("hello");
//        future.addListener(new ChannelFutureListener() {
//            @Override
//            public void operationComplete(ChannelFuture channelFuture) throws Exception {
//                if (channelFuture.isSuccess()) {
//                    System.out.println("发送成功");
//                } else {
//                    System.out.println("发送失败");
//                    channelFuture.cause().printStackTrace();
//                }
//            }
//        });
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        String response = msg.toString(CharsetUtil.UTF_8);
        logger.info("客户端收到服务端响应数据:"+response);
        JSONObject jsonObject = JSONObject.parseObject(response);
        String requestId = jsonObject.getString("requestId");
        jsonObject.remove("requestId");
        String result = jsonObject.toJSONString();
        ClientService.RESULT_MAP.put(requestId,result);
    }

    private JSONObject getJSONObject(String str){
        JSONObject json = JSONObject.parseObject(str);
        json.remove("content");
        json.put("msg","保存用户信息成功");
        return json;
    }

}
